// 要删除房屋的id和索引
let house_id = ''
let house_index = 0
Page({
  data: {
    dialogVisible: false,
    houseList: [],
  },

  onShow() {
    this.getHouseList()
  },

  // 1. 关闭滑动单元格
  closeSwipe(ev) {
    const { position, instance } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // 记录要删除房屋的id和索引
      house_id = ev.mark.house_id
      house_index = ev.mark.house_index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  // 2. 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败')
    this.setData({
      houseList,
    })
  },

  // 3. 删除房屋
  dialogClose(e) {
    // 3.1 判断用户点击了确认
    // if(e.detail === 'confirm'){
    //   this.deleteHouse()
    // }
    e.detail === 'confirm' && this.removeHouse()
  },

  async removeHouse() {
    const { code } = await wx.http.delete(`/room/${house_id}`)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')
    wx.utils.toast('删除房屋成功')
    // 从房屋数组中移除要删除的房屋
    const { houseList } = this.data
    //
    houseList.splice(house_index, 1)
    this.setData({
      houseList,
    })
  },

  // 4. 去详情页
  goDetail(e) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + e.mark.id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
